import React, { useEffect, useState } from "react";
import { Button, Table, message, Popconfirm, DatePicker } from "antd";
import {
  listPurchaseNotification,
  createPurchaseNotification,
  listProducts,
  listUsers,
  listRoles,
} from "../../api/ckgl";
import PurchaseNotificationModal from "./componets/PurchaseNotificationModal";

const ListPurchaseNotifications = () => {
  const [purchaseNotificationList, setPurchaseNotificationList] = useState<
    any[]
  >([]);
  const [totalPurchaseNotifications, setTotalPurchaseNotifications] =
    useState(0);
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize] = useState(10);
  const [
    isPurchaseNotificationModalVisible,
    setIsPurchaseNotificationModalVisible,
  ] = useState(false);
  const [currentPurchaseNotification, setCurrentPurchaseNotification] =
    useState<any>(null);
  const [productList, setProductList] = useState<any[]>([]);
  const [list, setList] = useState<any[]>([]);

  const columns = [
    {
      title: "ID",
      dataIndex: "id",
      key: "id",
    },
    {
      title: "物品",
      dataIndex: "product_name",
      key: "product_name",
      render: (text: string) => <span>{text}</span>,
    },
    {
      title: "接收人id",
      dataIndex: "recipient_name",
      key: "recipient_name",
      render: (text: string) => <span>{text}</span>,
    },
    {
      title: "采购数量",
      dataIndex: "quantity",
      key: "quantity",
      render: (text: string) => <span>{text}</span>,
    },
  ];

  const getListPurchaseNotifications = (page: number) => {
    // 调用 listPurchaseNotifications API，并处理响应
    let recipient_id =
      localStorage?.role_code === "admin" ? undefined : localStorage?.user_id;
    listPurchaseNotification({
      page,
      size: pageSize,
      recipient_id,
      // int32 recipient_id = 3; // 接收人id(采购人员), 当前登陆采购人员只能看到自己的采购通知
    }).then((res: any) => {
      if (res?.code !== 0) {
        message.error(res.msg);
        return;
      }
      const { purchase_notifications, total } = res.data;
      setPurchaseNotificationList(purchase_notifications);
      setTotalPurchaseNotifications(total);
    });
  };

  const reset = (page: number) => {
    getListPurchaseNotifications(page);
  };

  const handlePurchaseNotificationModalOk = async (values: any) => {
    // 根据情况调用 createPurchaseNotification 或 updatePurchaseNotification API，并处理响应
    if (currentPurchaseNotification) {
    } else {
      // 添加
      let msg = "添加成功";
      await createPurchaseNotification({
        ...values,
      }).then((res: any) => {
        // if (res?.code !== 0) {
        //   message.error(res.msg);
        //   return;
        // }
        message.success(msg);
      });
    }
    reset(currentPage);
    setIsPurchaseNotificationModalVisible(false);
  };

  useEffect(() => {
    getListPurchaseNotifications(currentPage);
  }, [currentPage]);

  useEffect(() => {
    getListProducts();
    getListUsers();
  }, []);

  const getListProducts = () => {
    // 调用 listProducts API，并处理响应
    listProducts({
      page: 1,
      size: 200,
    }).then((res: any) => {
      if (res?.code !== 0) {
        message.error(res.msg);
        return;
      }
      const { products, total } = res.data;
      setProductList(products);
    });
  };

  const getListUsers = () => {
    // 获取 roles
    listRoles({
      page: 1,
      size: 100,
    }).then(async (res: any) => {
      if (res?.code !== 0) {
        message.error(res.msg);
        return;
      }
      const { roles } = res.data;
      console.log("roles", roles);
      let currentRole = roles.find((ele: any) => ele.code === "purchaser");
      let roleId = currentRole.id;
      listUsers({
        page: 1,
        size: 300,
        role_id: roleId,
      }).then((res: any) => {
        console.log(res);
        if (res?.code !== 0) {
          message.error(res.msg);
          return;
        }
        // admin(系统管理员)，purchaser（采购人员），m-admin（物资管理员），picker（领物），visitor（游客）
        const { users, total } = res.data;

        setList(users);
      });
    });
  };

  return (
    <div>
      {!["purchaser"].includes(localStorage?.role_code) && (
        <Button
          style={{ marginTop: "7px", marginLeft: "10px", float: "right" }}
          onClick={() => {
            setIsPurchaseNotificationModalVisible(true);
            setCurrentPurchaseNotification(null);
          }}
          size="large"
          type="primary"
        >
          添加采购提醒
        </Button>
      )}

      <Table
        dataSource={purchaseNotificationList}
        columns={columns}
        rowKey="id"
        pagination={{
          pageSize,
          defaultCurrent: 1,
          onChange: setCurrentPage,
          total: totalPurchaseNotifications,
        }}
      />
      <PurchaseNotificationModal
        users={list}
        productList={productList}
        title={"添加采购提醒"}
        visible={isPurchaseNotificationModalVisible}
        onCancel={() => setIsPurchaseNotificationModalVisible(false)}
        onOk={handlePurchaseNotificationModalOk}
        defaultValue={{}}
      />
    </div>
  );
};

export default ListPurchaseNotifications;
